﻿//"The contents of this file are subject to the Mozilla Public License
//Version 1.1 (the "License"); you may not use this file except in
//compliance with the License. You may obtain a copy of the License at
//http://www.mozilla.org/MPL/

//Software distributed under the License is distributed on an "AS IS"
//basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
//License for the specific language governing rights and limitations
//under the License.

//The Original Code is TSharp.

//The Initial Developer of the Original Code is Mar3ek (http://mar3ek.wordpress.com).
//Portions created by Mar3ek are Copyright (C) 2010
//Mar3ek (http://mar3ek.wordpress.com). All Rights Reserved.

//Contributor(s): ______________________________________.

//Alternatively, the contents of this file may be used under the terms
//of the _____ license (the  "[___] License"), in which case the
//provisions of [______] License are applicable instead of those
//above.  If you wish to allow use of your version of this file only
//under the terms of the [____] License and not to allow others to use
//your version of this file under the MPL, indicate your decision by
//deleting  the provisions above and replace  them with the notice and
//other provisions required by the [___] License.  If you do not delete
//the provisions above, a recipient may use your version of this file
//under either the MPL or the [___] License."

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Xml.Linq;

namespace TSharp
{
    public partial class Twitter
    {
        #region Saved searches

        ///<summary>
        /// Returns the authenticated user's saved search queries.
        ///</summary>
        ///<returns>List of saved searches</returns>
        public Collection<SavedSearch> GetSavedSearches()
        {
            var result = SendRequest(RequestMethod.Get, "https://api.twitter.com/1/saved_searches.xml",
                                     true);

            var doc = XDocument.Parse(result);
            var collection = new Collection<SavedSearch>();
            var savedSearchesElement = doc.Element("saved_searches");

            if (savedSearchesElement != null)
                foreach (var ssElement in savedSearchesElement.Elements("saved_search"))
                {
                    collection.Add(ParseSavedSearch(ssElement));
                }

            return collection;
        }

        ///<summary>
        /// Retrieve the data for a saved search owned by the authenticating user specified by the given id.
        ///</summary>
        ///<param name="searchId">The ID of the saved search</param>
        ///<returns>Saved search</returns>
        public SavedSearch GetSavedSearch(ulong searchId)
        {
            var result = SendRequest(RequestMethod.Get,
                                     string.Format("https://api.twitter.com/1/saved_searches/show/{0}.xml", searchId),
                                     true);

            var doc = XDocument.Parse(result);

            return ParseSavedSearch(doc.Element("saved_search"));
        }

        ///<summary>
        /// Creates a saved search for the authenticated user.
        ///</summary>
        ///<param name="query">The query of the search the user would like to save</param>
        ///<returns>Saved search</returns>
        public SavedSearch CreateSavedSearch(string query)
        {
            var result = SendRequest(RequestMethod.Post, "https://api.twitter.com/1/saved_searches/create.xml",
                                     false, new KeyValuePair<string, string>("query", Globals.ProperUrlEscape(query)));

            var doc = XDocument.Parse(result);

            return ParseSavedSearch(doc.Element("saved_search"));
        }

        #region DeleteSavedSearch

        ///<summary>
        /// Destroys a saved search for the authenticated user.
        ///</summary>
        ///<param name="searchId">The ID of the saved search</param>
        ///<returns>Destroyed saved search</returns>
        /// <remarks>The search specified by id must be owned by the authenticating user.</remarks>
        public SavedSearch DeleteSavedSearch(ulong searchId)
        {
            var result = SendRequest(RequestMethod.Delete,
                                     string.Format("http://api.twitter.com/version/saved_searches/destroy/{0}.format",
                                                   searchId),
                                     false);

            var doc = XDocument.Parse(result);

            return ParseSavedSearch(doc.Element("saved_search"));
        }

        ///<summary>
        /// Destroys a saved search for the authenticated user.
        ///</summary>
        ///<param name="search">The saved search to delete</param>
        ///<returns>Destroyed saved search</returns>
        /// <remarks>The search specified by id must be owned by the authenticating user.</remarks>
        /// <exception cref="ArgumentNullException"><paramref name="search" /> is <c>null</c>.</exception>
        public SavedSearch DeleteSavedSearch(SavedSearch search)
        {
            if (search == null) throw new ArgumentNullException("search");

            return DeleteSavedSearch(search.Id);
        }

        #endregion

        #endregion

        /// <exception cref="ArgumentNullException"><paramref name="ssElement" /> is <c>null</c>.</exception>
        private static SavedSearch ParseSavedSearch(XContainer ssElement)
        {
            if (ssElement == null) throw new ArgumentNullException("ssElement");
            // ReSharper disable PossibleNullReferenceException
            return new SavedSearch(ulong.Parse(ssElement.Element("id").Value),
                                   ssElement.Element("name").Value, ssElement.Element("query").Value,
                                   ParseTiwtterTime(ssElement.Element("created_at").Value));
            // ReSharper restore PossibleNullReferenceException
        }
    }
}
